package vn.hut.soict.cs.phanquanghuy.neslegend.emulator.memory;

import vn.hut.soict.cs.phanquanghuy.neslegend.emulator.util.NumberUtil;

public class IORegisters implements IMemory {
	public final static int IOREGISTERS_OFFSET = 0x2000;
	public final static int IOREGISTERS_SIZE = 	0x4020;	
	
	public final static int MIRROR_AREA_START_RELATIVE = 0x0008;
	public final static int MIRROR_AREA_BAND_COUNT = 0x3ff;

	private int[] dataBlocks;
	
	public IORegisters() {
		this.dataBlocks = new int[IOREGISTERS_SIZE];
		clear();
	}

	@Override
	public int readMemory(int physicAddress) {
		return dataBlocks[physicAddress - IOREGISTERS_OFFSET];
	}

	@Override
	public void writeMemory(int physicAddress, int value) {
		final int relativeAddr = physicAddress - IOREGISTERS_OFFSET;
		
		dataBlocks[relativeAddr] = NumberUtil.roundByte(value);
		
		//MIRROR
		if (relativeAddr >= 0x0000 && relativeAddr < 0x0008) {
			for (int index = 0x0000; index <= MIRROR_AREA_BAND_COUNT; index++) {
				dataBlocks[relativeAddr + 0x0008 * index + MIRROR_AREA_START_RELATIVE] = dataBlocks[relativeAddr];
			}
		}
	}

	@Override
	public void clear() {
		
	}

	@Override
	public int offset() {
		return IOREGISTERS_OFFSET;
	}

	@Override
	public int length() {
		return IOREGISTERS_SIZE;
	}

}
